package com.cenntro.oss.controller;

import java.util.Date;
import java.util.List;

import javax.annotation.Resource;

import org.springframework.util.Assert;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.alibaba.fastjson.JSON;
import com.cenntro.common.base.BaseController;
import com.cenntro.common.door.SocketUtil;
import com.cenntro.common.util.result.PageResult;
import com.cenntro.common.util.result.Result;
import com.cenntro.oss.model.dbo.DevDeviceOnlineDO;
import com.cenntro.oss.model.dbo.DevDeviceStaticDO;
import com.cenntro.oss.model.dbo.DevOperateDO;
import com.cenntro.oss.model.dbo.SysAgentDO;
import com.cenntro.oss.model.vo.DeviceVO;
import com.cenntro.oss.service.DevDeviceOnlineService;
import com.cenntro.oss.service.DevDeviceStaticService;
import com.cenntro.oss.service.DevOperateService;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.google.common.collect.ImmutableMap;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;

/**
 * <p>
 * 车辆主动下行操作日志表 
 * </p>
 *
 * @author
 * @since 2018-09-17
 */
@Slf4j
@Api(value = "操作记录", tags = { "操作记录" })
@RestController
@RequestMapping("/operate")
public class DevOperateController extends BaseController {

    @Resource
    private DevOperateService devOperateService;

    @Resource
    private DevDeviceStaticService devDeviceStaticService;

    @Resource
    private DevDeviceOnlineService devDeviceOnlineService;

    /**
     * 操作记录列表
    * @Title selectPage
    * @Description 操作记录列表，开门关门等
    * @param 
    * @return  
    * @throws
     */
    @RequestMapping("/selectPage")
    public Result selectPage(DeviceVO dev) {
        DevOperateDO opt = new DevOperateDO();
        // opt.setImei(dev.getImei()); 无该字段
        // opt.setVinCode(dev.getVincode());
        // opt.setStartTime(dev.getStartTime());
        // opt.setEndTime(dev.getEndTime());
        Page<SysAgentDO> page = PageHelper.startPage(dev.getPage(), dev.getLimit(), true);
        List<DevOperateDO> ops = devOperateService.selectPage(opt);
        return PageResult.ok(ops, page.getTotal());
    }

    /**
     * 
    * @Title openDoor
    * @Description 指令开门操作
    * @param devId
    * @return  
    * @throws
     */
    @CrossOrigin
    @ApiOperation(value = "车辆开门", notes = "车辆开门")
    @RequestMapping(value = "/openDoor")
    public Object openDoor(Integer devId) {
        DevDeviceStaticDO dsd = devDeviceStaticService.selectById(devId);
        Assert.isTrue(dsd != null, "车辆不存在");
        DevDeviceOnlineDO dod = devDeviceOnlineService.selectOne(ImmutableMap.of("devId", dsd.getDevId()));
        Assert.isTrue(dod != null, "车辆不存在");
        log.info("dod: {}", JSON.toJSONString(dod));
        if (Integer.valueOf(0).equals(dod.getDeviceStatus())) {
            return Result.error("车辆已离线，无法开门/锁门");
        }
        if (dod.getDeviceStatus().equals(0)) {
            return Result.error("车辆已离线，无法远程开门/锁门");
        }
        if (dod.getFire().equals(1)) {
            return Result.error("车辆已启动，无法远程开门/锁门");
        }

        String upid = String.valueOf(((int) ((Math.random() * 9 + 1) * 100000)));
        String command = "<C006," + dsd.getImei() + "," + upid + ",1002>";
        String result = SocketUtil.GetInstance().SendMsg(command, dod.getIpPort());
        if (result.equals("success")) {
            // 插入一次操作记录
            DevOperateDO model = new DevOperateDO();
            model.setDevId(devId);
            model.setCommand(command);
            model.setInfo("开锁");
            model.setUpIndex(upid);
            model.setCity(dod.getCity());
            model.setStatus("已发送到连接池");
            model.setCreateTime(new Date());
            devOperateService.insert(model);
            return Result.ok();
        }
        return Result.error("操作开门失败");
    }

    /**
     * 关门操作
     * @param devId
     * @return
     */
    @RequestMapping("/closeDoor")
    @CrossOrigin
    @ApiOperation(value = "关门", notes = "关门")
    public Object closeDoor(Integer devId) {
        Result result = Result.error("操作失败");
        DevDeviceStaticDO dsd = devDeviceStaticService.selectById(devId);
        Assert.isTrue(dsd != null, "车辆不存在");
        DevDeviceOnlineDO dod = devDeviceOnlineService.selectOne(ImmutableMap.of("devId", dsd.getDevId()));
        Assert.isTrue(dod != null, "车辆不存在");
        log.info("dod: {}", JSON.toJSONString(dod));
        if (Integer.valueOf(0).equals(dod.getDeviceStatus())) {
            return Result.error("车辆已离线，无法锁车");
        }
        if (dod.getFire() != null && dod.getFire().equals(1)) {
            return Result.error("车辆已启动，无法锁车");
        }
        if (dod.getDoor() != null && dod.getDoor().equals(2)) {
            return Result.error("右门已开启，请确认门关闭后重试");
        }
        if (dod.getDoor() != null && dod.getDoor().equals(4)) {
            return Result.error("左门已开启，请确认门关闭后重试");
        }
        if (dod.getDoor() != null && dod.getDoor().equals(0)) {
            return Result.error("门已开启，请确认门关闭后重试");
        }

        String upid = String.valueOf(((int) ((Math.random() * 9 + 1) * 100000)));
        String command = "<C006," + dsd.getImei() + "," + upid + ",1001>";
        String resultText = SocketUtil.GetInstance().SendMsg(command, dod.getIpPort());
        if (resultText.equals("success")) {
            // 插入一次操作记录
            DevOperateDO model = new DevOperateDO();
            model.setDevId(devId);
            model.setCommand(command);
            model.setInfo("关锁");
            model.setUpIndex(upid);
            model.setCity(dod.getCity());
            model.setStatus("已发送到连接池");
            model.setCreateTime(new Date());
            devOperateService.insert(model);
            return Result.ok();
        }
        return result;
    }

}
